package cn.cjlmonster.hyouka_assistant.json;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.lang.reflect.Type;
import java.util.List;

/**
 * JTools
 * @author cjl
 */
public class JTools {

    private static final Gson gson = new GsonBuilder().create();

    private static final Gson gsonPretty = new GsonBuilder().setPrettyPrinting().create();

    public static String toJsonPretty(Object obj) {
        return gsonPretty.toJson(obj);
    }

    public static String toJson(Object obj) {
        return gson.toJson(obj);
    }

    public static <T> T toObj(String jsonString, Class<T> classOfT) {
        try {
            return gson.fromJson(jsonString, classOfT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> List<T> toList(String jsonString, Class<T> classOfT) {
        try {
            Type type = new ParameterizedTypeImpl<>(classOfT);
            return gson.fromJson(jsonString, type);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
